<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card class="box-card">
      <!-- 搜索与添加区域 -->
      <el-row :gutter="20">
        <el-col :span="8"
          ><el-input
            placeholder="请输入内容"
            v-model="queryInfo.query"
            clearable
            @clear="getUserList()"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUserList()"
            ></el-button> </el-input
        ></el-col>
        <el-col :span="6">
          <el-button type="primary" @click="addUserVisible = true"
            >添加用户</el-button
          ></el-col
        >
        <!-- 添加用户弹窗 -->
        <el-dialog
          title="添加用户"
          :visible.sync="addUserVisible"
          width="30%"
          @close="addDialogClosed"
        >
          <el-form
            ref="addUserFormRef"
            :model="addUserForm"
            :rules="addUserRules"
            label-width="80px"
          >
            <el-form-item label="用户名" prop="username">
              <el-input v-model="addUserForm.username"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-input
                v-model="addUserForm.password"
                type="password"
              ></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="addUserForm.email" type="email"></el-input>
            </el-form-item>
            <el-form-item label="手机号" prop="mobile">
              <el-input v-model="addUserForm.mobile"></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer">
            <el-button @click="addUserVisible = false">取 消</el-button>
            <el-button type="primary" @click="addUser">确 定</el-button>
          </span>
        </el-dialog>
      </el-row>
      <!-- 列表数据显示区域 -->
      <el-table :data="usersInfo.users" stripe style="width: 100%" border>
        <el-table-column type="index" label="#"> </el-table-column>
        <el-table-column prop="username" label="姓名" width="100">
        </el-table-column>
        <el-table-column prop="email" label="邮箱"> </el-table-column>
        <el-table-column prop="mobile" label="手机号"> </el-table-column>
        <el-table-column prop="role_name" label="角色"> </el-table-column>
        <el-table-column label="状态" align="center">
          <!-- 通过作用域插槽接收值，再用这个值点row 获取这一行的数据  比react获取值简单 -->
          <template v-slot="scope">
            <el-switch
              v-model="scope.row.mg_state"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="userStateChange(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" class="caozuo" align="center">
          <template v-slot="scope">
            <!-- 修改按钮 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEditDialog(scope.row.id)"
              style="margin-right: 10px"
            ></el-button>
            <el-dialog
              title="提示"
              :visible.sync="editdialogVisible"
              width="30%"
            >
              <el-form
                ref="editUserInfoFormRef"
                :model="editUserInfoForm"
                :rules="addUserRules"
                label-width="80px"
              >
                <el-form-item label="用户名" prop="username">
                  <el-input
                    v-model="editUserInfoForm.username"
                    disabled
                  ></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                  <el-input v-model="editUserInfoForm.email"></el-input>
                </el-form-item>
                <el-form-item label="手机号" prop="mobile">
                  <el-input v-model="editUserInfoForm.mobile"></el-input>
                </el-form-item>
              </el-form>
              <span slot="footer" class="dialog-footer">
                <el-button @click="editdialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="editUserInfo"
                  >确 定</el-button
                >
              </span>
            </el-dialog>
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="deleteUserInfo(scope.row.id)"
            ></el-button>

            <!-- 分配角色按钮 -->
            <el-tooltip
              effect="dark"
              content="分配角色"
              placement="top-start"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="setRole(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="usersInfo.total"
      >
      </el-pagination>
    </el-card>

    <!-- 点击分配角色的对话框 -->
    <el-dialog
      title="分配角色"
      :visible.sync="setRoleDialogVisible"
      @close="setRoleDialogVisibleClosed"
    >
      <div>
        <p style="margin-bottom: 10px">当前用户：{{ roleuserInfo.username }}</p>
        <p style="margin-bottom: 10px">
          当前角色：{{ roleuserInfo.role_name }}
        </p>
        分配新角色：
        <el-select v-model="selectRoleId" placeholder="请选择">
          <el-option
            v-for="item in rolesList"
            :key="item.id"
            :label="item.roleName"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script type="text/ecmascript-6">
import {
  reqUsers,
  reqUserState,
  reqAddUsers,
  reqQueryUserInfo,
  reqEditUserInfo,
  reqDeleteUserInfo,
  reqRoles,
  reqUserRole,
} from "../../api";
export default {
  data() {
    return {
      // 发用户数据列表请求 的get请求参数
      queryInfo: {
        query: "",
        pagenum: 1, //当前的页数
        pagesize: 2, //每页多少条
      },
      usersInfo: {},
      addUserVisible: false, //是否显示添加用户弹窗
      // 添加用户的表单
      addUserForm: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      // 添加用户的检验规则
      addUserRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "长度在 3 到 15 个字符",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 3,
            max: 15,
            message: "长度在 3 到 15 个字符",
            trigger: "blur",
          },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: this.checkEmail, trigger: "blur" },
          {
            min: 3,
            max: 15,
            message: "长度在 3 到 15 个字符",
            trigger: "blur",
          },
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: this.checkMobile, trigger: "blur" },
          {
            min: 11,
            max: 11,
            message: "长度为11 个字符",
            trigger: "blur",
          },
        ],
      },
      // 编辑用户信息弹窗
      editdialogVisible: false,
      // 编辑用户信息的表单
      editUserInfoForm: {},
      // 点击按钮，删除用户弹窗
      deleteialogVisible: false,
      // 显示隐藏分配角色对话框
      setRoleDialogVisible: false,
      // 需要被分配角色的用户信息
      roleuserInfo: {},
      // 所有角色列表
      rolesList: [],
      // 被选择分配的角色的id值
      selectRoleId: "",
    };
  },
  mounted() {
    this.getUserList();
  },
  methods: {
    async getUserList() {
      const result = await reqUsers(this.queryInfo);
      if (result.meta.status !== 200)
        return this.$message.error(result.meta.msg);
      else {
        this.usersInfo = result.data;
      }
    },
    // 监听pagesize 每页多少条改变的事件
    handleSizeChange(pagesize) {
      // console.log(`每页 ${pagesize} 条`);
      this.queryInfo.pagesize = pagesize;
      this.getUserList();
    },
    // 监听pagenum 当前页码改变的事件
    handleCurrentChange(pagenum) {
      // console.log(`当前页: ${pagenum}`);
      this.queryInfo.pagenum = pagenum;
      this.getUserList();
    },
    // 监听userStateChange用户状态改变
    async userStateChange(user) {
      console.log(user);
      const result = await reqUserState(user);
      console.log(result);
    },
    // 自定义验证邮箱的校验规则
    checkEmail(rule, value, callback) {
      const regEmail = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;
      if (regEmail.test(value)) callback();
      else callback(new Error("邮箱不合法"));
    },
    // 自定义验证手机号的校验规则
    checkMobile(rule, value, callback) {
      const regMobile =
        /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/;
      if (regMobile.test(value)) callback();
      else callback(new Error("手机号不合法"));
    },
    // 监听添加用户框的关闭事件
    addDialogClosed() {
      this.$refs.addUserFormRef.resetFields();
    },
    // 点击按钮，向后台发请求，添加新用户
    addUser() {
      // 预检验
      this.$refs.addUserFormRef.validate(async (valid) => {
        if (!valid) return;
        else {
          // 发请求添加新用户
          const result = await reqAddUsers(this.addUserForm);
          const { meta } = result;
          console.log(result);
          if (meta.status >= 200 && meta.status <= 300) {
            // 成功
            this.getUserList();
            this.$message.success(meta.msg);
            // 隐藏添加用户对话框
            this.addUserVisible = false;
          } else {
            // 失败
            this.$message.error(meta.msg);
            // 隐藏添加用户对话框
            this.addUserVisible = false;
          }
        }
      });
    },
    // 点击按钮，展示编辑用户信息
    async showEditDialog(id) {
      this.editdialogVisible = true;
      const result = await reqQueryUserInfo(id);
      this.editUserInfoForm = result.data;
    },
    // 点击按钮，编辑用户信息
    editUserInfo() {
      this.$refs.editUserInfoFormRef.validate(async (valid) => {
        if (!valid) return;
        else {
          // 发网络请求编辑数据
          const { email, mobile, id } = this.editUserInfoForm;
          const result = await reqEditUserInfo({
            email,
            mobile,
            id,
          });
          // 成功
          if (result.meta.status === 200) {
            this.getUserList();
            this.$message.success(result.meta.msg);
            // 关闭对话框
            this.editdialogVisible = false;
          } else {
            // 失败
            this.$message.error(result.meta.msg);
          }
        }
      });
    },
    // 删除用户信息
    deleteUserInfo(id) {
      this.$confirm("此操作将删除用户信息, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const result = await reqDeleteUserInfo(id);
          if (result.meta.status != 200) return;
          this.$message.success(result.meta.msg);
          this.getUserList();
        })
        .catch(() => {});
    },
    //展示分配角色的对话框
    async setRole(userInfo) {
      this.roleuserInfo = userInfo;
      this.setRoleDialogVisible = true;

      const result = await reqRoles();
      if (result.meta.status != 200) this.$message.error(result.meta.msg);
      this.rolesList = result.data;
    },
    // 点击确认按钮，分配角色
    async saveRoleInfo() {
      if (!this.selectRoleId) return this.$message.error("请选择分配的角色");

      const result = await reqUserRole(this.roleuserInfo.id, this.selectRoleId);
      if (result.meta.status != 200) this.$message.error(result.meta.msg);
      this.$message.success(result.meta.msg);
      this.getUserList();
      this.setRoleDialogVisible = false;
    },
    // 监听分配对话框关闭时的关闭事件
    setRoleDialogVisibleClosed() {
      this.selectRoleId = "";
      this.roleuserInfo = {};
    },
  },
};
</script>

<style lang="less" scoped>
.el-table {
  margin-top: 15px;
}
.caozuo {
  display: flex;
}
</style>

